<template>
  <div>
    <CustomTable 
      class="customTable"
      rowKey="id"
      title="任务列表" 
      :dataSource="dataSource" 
      :columns="columns" 
      :loading="loading"
      :downloadTitle="downloadTitle"
      :pagination="{showTotal:total => `共 ${total} 条数据`, pageSize: pageSize,showLessItems: true, showSizeChanger:true,pageSizeOptions:['10', '20', '50', '100']}"
      :scroll="{x:1200}"
    >
      <div style="display: flex;justify-content: space-between;;margin-bottom: 20px;">
        <addTask @confirm="getTasks" />
        <a-popconfirm title="确定清理计划吗" ok-text="清理" cancel-text="取消" @confirm="startTask">
          <a-button type="danger" style="margin-left: 10px;" :loading="clearLoading">
            清理计划
          </a-button>
        </a-popconfirm>
      </div>
      <div slot="name" slot-scope="{record}" >
        <a-tooltip placement="topLeft" v-if="record.xmod == 'normal'">
          <template slot="title">
            {{record.name}}
          </template>
          <span style="display: block;cursor: pointer;white-space: nowrap;">{{record.name}}</span>
        </a-tooltip>
        <div v-else-if="record.xmod == 'edit'">
          <a-input v-model="record.name" />
        </div>
      </div>
      <div slot="account" slot-scope="{record}" >
        <div v-if="record.xmod == 'normal'">
          <!-- <a-tooltip>
            <template slot="title">
              {{record.account}}
            </template>
          </a-tooltip> -->
          <span v-for="(item,index) in record.accounts" :key="index">
            <a :href="'https://shoppingads.baidu.com/shop/manageCenter/dashboard/campaignList/target/0/user/'+item.ucid" target="_blank" >
              {{item.account}}
              <span v-if="index < record.accounts.length - 1">,</span>
            </a>
          </span>
        </div>
        <div v-else-if="record.xmod == 'edit'">
          <a-select
            mode="multiple"
            v-model="record.accountArr"
            style="width: 100%;"
            @change="accountSelect(record.id)"
            @search="accountSelectSearch"
          >
            <a-select-option :value="item.account" v-for="(item, index) in accountList" :key="index">
              {{ item.account }}
            </a-select-option>
          </a-select>
        </div>
      </div>
      <div slot="admin_userid" slot-scope="{record}" >
        {{ setUserName(record.admin_userid) }}
      </div>
      <div slot="action" slot-scope="{record}" >
        <a v-if="record.xmod == 'normal'" style="margin-right: 8px" href="javascript:;" v-auth="`edit`" @click="showStrategie(record.id, record.name)">
          <a-icon type="setting"/>
          <span style="margin-left: 2px;">策略</span>
        </a>
        <a v-if="record.xmod == 'normal'" style="margin-right: 8px" href="javascript:;" v-auth="`edit`" @click="edit(record.id)">
          <a-icon type="edit"/>
          <span style="margin-left: 2px;">编辑</span>
        </a>
        <a v-else-if="record.xmod == 'edit'" style="margin-right: 8px" href="javascript:;" v-auth="`edit`" @click="save(record.id)">
          <a-icon type="save"/>
          <span style="margin-left: 2px;">保存</span>
        </a>
        <a style="margin-right: 8px" href="javascript:;" v-auth="`edit`" @click="showAuto(record.id, record.name)">
          <a-icon type="dashboard"/>
          <span style="margin-left: 2px;">批量调价</span>
        </a>
        <a-popconfirm v-if="record.xmod == 'normal'" title="确定删除？" ok-text="删除" cancel-text="取消" @confirm='deleteRecord(record.id)' v-auth="`delete`">
          <a-button type="link" style="padding: 0;">
            <a-icon type="delete" /> 
            <span style="margin-left: 2px;">删除</span>
          </a-button>
        </a-popconfirm>
        <a v-else-if="record.xmod == 'edit'" style="margin-right: 8px" href="javascript:;" v-auth="`edit`" @click="close(record.id)">
          <a-icon type="delete"/>
          <span style="margin-left: 2px;">取消</span>
        </a>
      </div>
    </CustomTable>
    <strategie :show.sync="showSG" :taskId="taskId" :taskName="taskName" />
    <auto :show.sync="autoStatus" :taskId="taskId" />
  </div>
</template>

<script>
import { Aitasktasks, delTask, updateTask, startTask } from '@/api/dianshang/dianshang'
import {getUsers} from '@/api/modules/manager'
import CustomTable from '@/components/table/CustomTable'
import addTask from './components/addTask.vue'
import strategie from './components/strategie.vue'
import auto from './components/piliangPrice.vue'
import {getAllBdAccountList} from '@/api/xinxiliu/account'

export default {
  data() {
    return {
      dataSource: [],
      loading: false,
      downloadTitle: '自动驾驶数据',
      columns: [
        {
          title: 'id',
          dataIndex: 'id',
          width: 80,
        },
        {
          title: '任务',
          width: 150,
          dataIndex: 'name',
          scopedSlots: {
            customRender: 'name'
          },
        },
        {
          title: '账户',
          dataIndex: 'account',
          width: 300,
          scopedSlots: {
            customRender: 'account'
          },
        },
        {
          title: '操作人',
          width: 100,
          dataIndex: 'admin_userid',
          scopedSlots: {
            customRender: 'admin_userid'
          },
        },
        {
          title: '创建时间',
          width: 180,
          dataIndex: 'create_time',
        },
        {
          title: '更新时间',
          width: 180,
          dataIndex: 'update_time',
        },
        {
          title: '操作',
          width: 250,
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        },
      ],
      pageSize: 10,
      userList: [],
      showSG: false, // 展现策略
      taskId: 0, // 当前的任务id，用于展现策略
      taskName: '', // 当前的任务name
      accountList: [],
      totalAccountList: [],
      clearLoading: false,
      autoStatus:false,
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.getData()
      this.getAllBdAccountList()
    },
    getData() {
      this.getUsers()
      this.getTasks()
    },
    getTasks() {
      // 获取任务列表
      this.loading = true
      Aitasktasks({}).then((res) => {
        this.loading = false
        if (res.errcode == 0) {
          for (let item of res.data) {
            item['xmod'] = 'normal'
            item['accountArr'] = item.account.split(',')
          }
          this.dataSource = res.data
        }
      }).catch(() => {
        this.loading = false
      });
    },
    getUsers(){
      // 获取优化师列表
      getUsers({}).then((res) => {
        if(res.errcode == 0){
          this.userList = res.data
        }
      });
    },
    getAllBdAccountList() {
      // 获取所有账户
      getAllBdAccountList({}).then((res) => {
        if (res.errcode == 0) {
          let accountList = res.data.filter(e => e.pid != 0)
          this.totalAccountList = accountList
          this.accountList = accountList.slice(0, 100)
          // console.log(this.accountList)
        }
      }).catch(() => {
        
      });
    },
    deleteRecord(id) {
      const hideLoad = this.$message.loading('删除中')
      delTask({ id }).then((res) => {
        hideLoad()
        if (res.errcode == 0) {
          this.getTasks()
        }
      }).catch(() => {
        hideLoad()
      });
    },
    startTask() { 
      this.clearLoading = true
      startTask({}).then((res) => {
        this.clearLoading = false
        if (res.errcode == 0) {
          this.$message.success('操作成功')
        }
      }).catch(() => {
        this.clearLoading = false
      });
    },
    save(id) {
      let item = this.dataSource.find(e => e.id == id)
      const params = {
        id:item.id,
        name:item.name,
        account:item.account
      }
      const hideLoad = this.$message.loading('更新中')
      updateTask(params).then((res) => {
        hideLoad()
        if (res.errcode == 0) {
          item['xmod'] = 'normal'
        }
      }).catch(() => {
        hideLoad()
      });
    },
    edit(id) {
      let item = this.dataSource.find(e => e.id == id)
      item['xmod'] = 'edit'
    },
    showAuto(id, name) {
      this.taskId = id
      this.taskName = name
      this.autoStatus = true
    },
    showStrategie(id, name) {
      this.taskId = id
      this.taskName = name
      this.showSG = true
    },
    setUserName(id) {
      let username = ''
      const account = this.userList.find(e => e.id == id)
      if (account) {
        username = account.username
      }
      return username
    },
    accountSelect(id) {
      // 设置account
      let item = this.dataSource.find(e => e.id == id)
      item.account = item.accountArr.join(',')
    },
    accountSelectSearch(value) {
      if (value != '') {
        this.accountList = this.totalAccountList.filter(e=>e.account.indexOf(value) >= 0).slice(0, 100)
      } else {
        this.accountList = this.totalAccountList.slice(0, 100)
      }
    },
    close(id) {
      let item = this.dataSource.find(e => e.id == id)
      item['xmod'] = 'normal'
    }
  },
  components:{CustomTable, addTask, strategie, auto},
}
</script>

<style lang="less" scoped>
</style>
